package ru.maksb.exchange.client;

import static ru.maksb.exchange.utils.PrintUtil.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import ru.maksb.exchange.utils.MessageSender;
import ru.maksb.exchange.utils.PrintUtil;

public class Client {
	private String host;
	private int port;
	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private BlockingQueue<String> messages = new LinkedBlockingDeque<String>();
	
	public Client(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void connect() {
		try {
			clientSysout("Trying to connect to " + host + ":" + port);
			socket = new Socket(host, port);
			clientSysout("Connected");
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
			new Thread(new MessageSender(messages , out)).start();
			new Thread(new SystemInHandler(messages, out)).start();
			InputHandler handler = new InputHandler(in, messages);
			handler.run();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void diconnect() {
		try {
			if (socket != null) {
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
        Client client = new Client("localhost", 1234);
        client.connect();
    }
}

